"""
Extension management CLI commands for GSM.

Provides commands for managing GSM extensions:
- gsm extension list: List available extensions
- gsm extension info <name>: Show extension information
- gsm extension enable/disable <name>: Enable/disable extensions
- gsm extension reload: Reload extensions
"""

import click
import logging
from typing import Optional

from ..extensions import get_registry, get_loader, get_router


logger = logging.getLogger(__name__)


@click.group(name='extension')
def extension_cli():
    """Manage GSM extensions."""
    pass


@extension_cli.command()
@click.option('--enabled-only', is_flag=True, help='Show only enabled extensions')
@click.option('--format', type=click.Choice(['table', 'json']), default='table', 
              help='Output format')
def list(enabled_only, format):
    """List available extensions."""
    try:
        registry = get_registry()
        
        if enabled_only:
            extensions = registry.get_enabled_extensions()
        else:
            extensions = registry.list_extensions()
        
        if not extensions:
            click.echo("No extensions found.")
            return
        
        if format == 'json':
            import json
            ext_data = []
            for ext in extensions:
                ext_data.append({
                    'name': ext.name,
                    'version': ext.version,
                    'enabled': ext.enabled,
                    'description': ext.description,
                    'frameworks': ext.supported_frameworks,
                    'solvers': ext.supported_solvers
                })
            click.echo(json.dumps(ext_data, indent=2))
        else:
            # Table format
            click.echo(f"Extensions ({len(extensions)} found):")
            click.echo("-" * 80)
            click.echo(f"{'NAME':<20} {'VERSION':<10} {'STATUS':<8} {'FRAMEWORKS':<20} {'DESCRIPTION'}")
            click.echo("-" * 80)
            
            for ext in extensions:
                status = "enabled" if ext.enabled else "disabled"
                frameworks = ", ".join(ext.supported_frameworks) if ext.supported_frameworks else "none"
                # Truncate long descriptions
                desc = ext.description[:30] + "..." if len(ext.description) > 30 else ext.description
                
                click.echo(f"{ext.name:<20} {ext.version:<10} {status:<8} {frameworks:<20} {desc}")
    
    except Exception as e:
        click.echo(f"❌ Error listing extensions: {e}")


@extension_cli.command()
@click.argument('name', required=True)
def info(name):
    """Show detailed information about an extension."""
    try:
        registry = get_registry()
        extension = registry.get_extension(name)
        
        if not extension:
            click.echo(f"❌ Extension '{name}' not found")
            return
        
        # Get metadata
        metadata = None
        for meta in registry.list_extensions():
            if meta.name == name:
                metadata = meta
                break
        
        if not metadata:
            click.echo(f"❌ Extension metadata for '{name}' not found")
            return
        
        # Display extension information
        click.echo(f"Extension: {metadata.name}")
        click.echo(f"Version: {metadata.version}")
        click.echo(f"Status: {'enabled' if metadata.enabled else 'disabled'}")
        click.echo(f"Description: {metadata.description}")
        
        click.echo(f"\nSupported Frameworks:")
        if metadata.supported_frameworks:
            for framework in metadata.supported_frameworks:
                click.echo(f"  - {framework}")
        else:
            click.echo("  (none)")
        
        click.echo(f"\nSupported Solvers:")
        if metadata.supported_solvers:
            for solver in metadata.supported_solvers:
                click.echo(f"  - {solver}")
        else:
            click.echo("  (none)")
        
        # Show configuration schema if available
        try:
            schema = extension.get_config_schema()
            if schema:
                click.echo(f"\nConfiguration Schema:")
                import json
                click.echo(json.dumps(schema, indent=2))
            else:
                click.echo(f"\nConfiguration Schema: (empty)")
        except Exception as e:
            click.echo(f"\nConfiguration Schema: (error retrieving: {e})")
        
        # Show available commands
        try:
            commands = extension.get_commands()
            if commands:
                click.echo(f"\nExtension Commands:")
                for cmd_name in commands.keys():
                    click.echo(f"  - {name}_{cmd_name}")
            else:
                click.echo(f"\nExtension Commands: (none)")
        except Exception as e:
            click.echo(f"\nExtension Commands: (error retrieving: {e})")
    
    except Exception as e:
        click.echo(f"❌ Error showing extension info: {e}")


@extension_cli.command()
@click.argument('name', required=True)
def enable(name):
    """Enable an extension."""
    try:
        registry = get_registry()
        
        if not registry.get_extension(name):
            click.echo(f"❌ Extension '{name}' not found")
            return
        
        if registry.enable_extension(name):
            click.echo(f"✅ Extension '{name}' enabled")
        else:
            click.echo(f"❌ Failed to enable extension '{name}'")
    
    except Exception as e:
        click.echo(f"❌ Error enabling extension: {e}")


@extension_cli.command()
@click.argument('name', required=True)
def disable(name):
    """Disable an extension."""
    try:
        registry = get_registry()
        
        if not registry.get_extension(name):
            click.echo(f"❌ Extension '{name}' not found")
            return
        
        if registry.disable_extension(name):
            click.echo(f"✅ Extension '{name}' disabled")
        else:
            click.echo(f"❌ Failed to disable extension '{name}'")
    
    except Exception as e:
        click.echo(f"❌ Error disabling extension: {e}")


@extension_cli.command()
@click.option('--verbose', '-v', is_flag=True, help='Show detailed output')
def reload(verbose):
    """Reload all extensions."""
    try:
        if verbose:
            click.echo("🔄 Reloading extensions...")
        
        loader = get_loader()
        results = loader.reload_extensions()
        
        successful = sum(1 for success in results.values() if success)
        total = len(results)
        
        if verbose:
            click.echo(f"\nReload results:")
            for file_path, success in results.items():
                status = "✅" if success else "❌"
                click.echo(f"  {status} {file_path}")
        
        click.echo(f"✅ Extension reload complete: {successful}/{total} files loaded successfully")
        
        # Show summary of loaded extensions
        registry = get_registry()
        extensions = registry.list_extensions()
        click.echo(f"📊 Total extensions available: {len(extensions)}")
        
    except Exception as e:
        click.echo(f"❌ Error reloading extensions: {e}")


@extension_cli.command()
@click.argument('config_file', type=click.Path(exists=True))
def detect(config_file):
    """Detect which extension can handle a configuration file."""
    try:
        from pathlib import Path
        
        config_path = Path(config_file)
        router = get_router()
        
        # Get framework info
        info = router.get_framework_info(config_path)
        
        click.echo(f"Configuration file: {config_path}")
        
        if info['supported']:
            click.echo(f"✅ Can be handled by extension: {info['extension']}")
            click.echo(f"Framework: {info['framework']}")
            click.echo(f"Extension version: {info['version']}")
        else:
            click.echo("❌ No extension found to handle this configuration")
            click.echo("💡 Available extensions:")
            
            registry = get_registry()
            extensions = registry.get_enabled_extensions()
            if extensions:
                for ext in extensions:
                    frameworks = ", ".join(ext.supported_frameworks) if ext.supported_frameworks else "none"
                    click.echo(f"  - {ext.name}: {frameworks}")
            else:
                click.echo("  (no extensions available)")
    
    except Exception as e:
        click.echo(f"❌ Error detecting extension: {e}")


# Export the main command group
extension_commands = extension_cli